package com.sosee.cgfw.camera;


import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Size;
import android.hardware.SensorManager;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.sosee.cgfw.R;
import com.sosee.cgfw.utils.Constans;
import com.sosee.cgfw.utils.LogUtils;
import com.sosee.cgfw.utils.Utils;
import com.lidroid.xutils.BitmapUtils;
import com.sosee.cgfw.view.ViewfinderView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import cn.sharesdk.wechat.utils.WechatHelper;

public class CameraFragment extends Fragment implements SurfaceHolder.Callback, Camera.PictureCallback, ViewPager.OnPageChangeListener, View.OnClickListener {

    public static final String TAG = CameraFragment.class.getSimpleName();
    public static final String CAMERA_ID_KEY = "camera_id";
    public static final String CAMERA_FLASH_KEY = "flash_mode";
    public static final String PREVIEW_HEIGHT_KEY = "preview_height";

    private static final int PICTURE_SIZE_MAX_WIDTH = 1280;
    private static final int PREVIEW_SIZE_MAX_WIDTH = 640;

    private int mCameraID;
    private String mFlashMode;
    private Camera mCamera;
    private SquareCameraPreview mPreviewView;
    private SurfaceHolder mSurfaceHolder;

    private int mDisplayOrientation;
    private int mLayoutOrientation;

    private int mCoverHeight;
    private int mPreviewHeight;
    private ViewPager vp;//
    private FragmentAdapter mAdapter;
    private List<Fragment> flist;//
    private int position=0;//
    private RelativeLayout rl_menu;//底部拍照菜单
    private RelativeLayout rl_share_menu;//底部分享菜单
    private ImageView ig;//关闭

    private CameraOrientationListener mOrientationListener;

    public static Fragment newInstance() {
        return new CameraFragment();
    }

    public CameraFragment() {}

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mOrientationListener = new CameraOrientationListener(activity);
    }






    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v=inflater.inflate(R.layout.fragment_camera, container, false);
        initViewPager(v);
        return v;
    }

    @Override
    public void onViewCreated(View view,  Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        LogUtils.log_E("测试fragment viewCreated");


        if (savedInstanceState == null) {
            mCameraID = getBackCameraID();
            mFlashMode = Camera.Parameters.FLASH_MODE_AUTO;
        } else {
            mCameraID = savedInstanceState.getInt(CAMERA_ID_KEY);
            mFlashMode = savedInstanceState.getString(CAMERA_FLASH_KEY);
            mPreviewHeight = savedInstanceState.getInt(PREVIEW_HEIGHT_KEY);
        }

        mOrientationListener.enable();

        mPreviewView = (SquareCameraPreview) view.findViewById(R.id.camera_preview_view);
        mPreviewView.getHolder().addCallback(CameraFragment.this);

        final View topCoverView = view.findViewById(R.id.cover_top_view);
        final View btnCoverView = view.findViewById(R.id.cover_bottom_view);

        if (mCoverHeight == 0) {
            ViewTreeObserver observer = mPreviewView.getViewTreeObserver();
            observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    int width = mPreviewView.getWidth();
                    mPreviewHeight = mPreviewView.getHeight();
                    mCoverHeight = (mPreviewHeight - width) / 2;

                    Log.d(TAG, "preview width " + width + " height " + mPreviewHeight);
                    topCoverView.getLayoutParams().height = 0;
                    btnCoverView.getLayoutParams().height = 0;

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        mPreviewView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    } else {
                        mPreviewView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    }
                }
            });
        } else {
            topCoverView.getLayoutParams().height = 0;
            btnCoverView.getLayoutParams().height = 0;
        }
        //打开系统相册
        final ImageView swapCameraBtn = (ImageView) view.findViewById(R.id.change_camera);
        swapCameraBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPhoto();
            }
        });

        final View changeCameraFlashModeBtn = view.findViewById(R.id.flash);
//        final TextView autoFlashIcon = (TextView) view.findViewById(R.id.auto_flash_icon);
        changeCameraFlashModeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (mFlashMode.equalsIgnoreCase(Camera.Parameters.FLASH_MODE_OFF)) {
//                    mFlashMode = Camera.Parameters.FLASH_MODE_TORCH;
////                    autoFlashIcon.setText("On");
//                } else if (mFlashMode.equalsIgnoreCase(Camera.Parameters.FLASH_MODE_TORCH)) {
//                    mFlashMode = Camera.Parameters.FLASH_MODE_OFF;
////                    autoFlashIcon.setText("Off");
//                }
////                else if (mFlashMode.equalsIgnoreCase(Camera.Parameters.FLASH_MODE_OFF)) {
////                    mFlashMode = Camera.Parameters.FLASH_MODE_AUTO;
//////                    autoFlashIcon.setText("Auto");
////                }
//
//                setupCamera();
                Camera.Parameters parameter;

                parameter = mCamera.getParameters();


                String status=parameter.getFlashMode();
                if(status.equals(Camera.Parameters.FLASH_MODE_TORCH)){
                    parameter.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);

                }else{
                    parameter.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);

                }


                mCamera.setParameters(parameter);




            }
        });

        final ImageView takePhotoBtn = (ImageView) view.findViewById(R.id.capture_image_button);
        takePhotoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takePicture();
            }
        });
    }




    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt(CAMERA_ID_KEY, mCameraID);
        outState.putString(CAMERA_FLASH_KEY, mFlashMode);
        outState.putInt(PREVIEW_HEIGHT_KEY, mPreviewHeight);
        super.onSaveInstanceState(outState);
    }
    private boolean camera=true;

    private void getCamera(int cameraID) {
        LogUtils.log_E("测试 getCamera");
        Log.d(TAG, "get camera with id " + cameraID);
        if(true){
            try {
                mCamera = Camera.open(cameraID);
                mPreviewView.setCamera(mCamera);
            } catch (Exception e) {
                Log.d(TAG, "Can't open camera with id " + cameraID);
                e.printStackTrace();
            }
        }

    }

    /**
     * Start the camera preview
     * //相机 重拍事件
     */
    private void startCameraPreview() {
        LogUtils.log_E("测试fragment camerapare");

        if(camera){
            ig_pic.setVisibility(View.GONE);
            rl_menu.setVisibility(View.VISIBLE);
            rl_share_menu.setVisibility(View.INVISIBLE);
            fl.setVisibility(View.VISIBLE);
            fl_new.setVisibility(View.INVISIBLE);
            determineDisplayOrientation();
            setupCamera();
            try {
                mCamera.setPreviewDisplay(mSurfaceHolder);
                mCamera.startPreview();
            } catch (IOException e) {
                Log.d(TAG, "Can't start camera preview due to IOException " + e);
                e.printStackTrace();
            }
        }else{
            ig_pic.setVisibility(View.VISIBLE);
            LogUtils.log_E("测试 else");
            rl_menu.setVisibility(View.INVISIBLE);
            rl_share_menu.setVisibility(View.VISIBLE);
            ig_fanzhuan.setVisibility(View.INVISIBLE);

//            pre.setVisibility(View.INVISIBLE);
//            fl.setVisibility(View.GONE);
//            fl_new.setVisibility(View.VISIBLE);
        }

    }


    //在fragment中处理 activity的返回键事件
    public void back(){
        if(!camera){
            camera=true;
            startCameraPreview();
        }else{
            getActivity().finish();
        }


    }

    /**
     * Stop the camera preview
     */
    private void stopCameraPreview() {
        // Nulls out callbacks, stops face detection
        mCamera.stopPreview();
        mPreviewView.setCamera(null);
    }

    /**
     * Determine the current display orientation and rotate the camera preview
     * accordingly
     */
    private void determineDisplayOrientation() {
        CameraInfo cameraInfo = new CameraInfo();
        Camera.getCameraInfo(mCameraID, cameraInfo);

        int rotation = getActivity().getWindowManager().getDefaultDisplay().getRotation();
        int degrees = 0;

        switch (rotation) {
            case Surface.ROTATION_0: {
                degrees = 0;
                break;
            }
            case Surface.ROTATION_90: {
                degrees = 90;
                break;
            }
            case Surface.ROTATION_180: {
                degrees = 180;
                break;
            }
            case Surface.ROTATION_270: {
                degrees = 270;
                break;
            }
        }

        int displayOrientation;

        // Camera direction
        if (cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT) {
            // Orientation is angle of rotation when facing the camera for
            // the camera image to match the natural orientation of the device
            displayOrientation = (cameraInfo.orientation + degrees) % 360;
            displayOrientation = (360 - displayOrientation) % 360;
        } else {
            displayOrientation = (cameraInfo.orientation - degrees + 360) % 360;
        }

        mDisplayOrientation = (cameraInfo.orientation - degrees + 360) % 360;
        mLayoutOrientation = degrees;

        mCamera.setDisplayOrientation(displayOrientation);
    }

    /**
     * Setup the camera parameters
     */
    private void setupCamera() {
        // Never keep a global parameters
        Camera.Parameters parameters = mCamera.getParameters();

        Size bestPreviewSize = determineBestPreviewSize(parameters);
        Size bestPictureSize = determineBestPictureSize(parameters);

        parameters.setPreviewSize(bestPreviewSize.width, bestPreviewSize.height);
        parameters.setPictureSize(bestPictureSize.width, bestPictureSize.height);


        // Set continuous picture focus, if it's supported
        if (parameters.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
        }

        final View changeCameraFlashModeBtn = getView().findViewById(R.id.flash);
        List<String> flashModes = parameters.getSupportedFlashModes();
        if (flashModes != null && flashModes.contains(mFlashMode)) {
            parameters.setFlashMode(mFlashMode);
            changeCameraFlashModeBtn.setVisibility(View.VISIBLE);
        } else {
            changeCameraFlashModeBtn.setVisibility(View.INVISIBLE);
        }

        // Lock in the changes
        mCamera.setParameters(parameters);
    }

    private Size determineBestPreviewSize(Camera.Parameters parameters) {
        return determineBestSize(parameters.getSupportedPreviewSizes(), PREVIEW_SIZE_MAX_WIDTH);
    }

    private Size determineBestPictureSize(Camera.Parameters parameters) {
        return determineBestSize(parameters.getSupportedPictureSizes(), PICTURE_SIZE_MAX_WIDTH);
    }

    private Size determineBestSize(List<Size> sizes, int widthThreshold) {
        Size bestSize = null;
        Size size;
        int numOfSizes = sizes.size();
        for (int i = 0; i < numOfSizes; i++) {
            size = sizes.get(i);
            boolean isDesireRatio = (size.width / 4) == (size.height / 3);
            boolean isBetterSize = (bestSize == null) || size.width > bestSize.width;

            if (isDesireRatio && isBetterSize) {
                bestSize = size;
            }
        }

        if (bestSize == null) {
            Log.d(TAG, "cannot find the best camera size");
            return sizes.get(sizes.size() - 1);
        }

        return bestSize;
    }

    private void restartPreview() {
        LogUtils.log_E("测试 restart");
        stopCameraPreview();
        mCamera.release();

        getCamera(mCameraID);
        startCameraPreview();
    }

    private int getFrontCameraID() {
        PackageManager pm = getActivity().getPackageManager();
        if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)) {
            return CameraInfo.CAMERA_FACING_FRONT;
        }

        return getBackCameraID();
    }

    private int getBackCameraID() {
        return CameraInfo.CAMERA_FACING_BACK;
    }

    /**
     * Take a picture
     */
    private void takePicture() {
//        mOrientationListener.rememberOrientation();
//
//        // Shutter callback occurs after the image is captured. This can
//        // be used to trigger a sound to let the user know that image is taken
//        Camera.ShutterCallback shutterCallback = null;
//
//        // Raw callback occurs when the raw image data is available
//        Camera.PictureCallback raw = null;
//
//        // postView callback occurs when a scaled, fully processed
//        // postView image is available.
//        Camera.PictureCallback postView = null;
//
//        // jpeg callback occurs when the compressed image is available

        //拍照
        mCamera.takePicture(null, null, new TakePictureCallback());
    }

    private String imgUrl;//从相册选择的图片的路劲；
    //打开系统相册  "image/*"
    //外网暂时未开放此功能
    private int RESULT_LOAD_IMAGE=0;
    public void getPhoto(){
        camera=false;
        Intent intent = new Intent(
                Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, RESULT_LOAD_IMAGE);
    }


    public void getPic_onResult(String url){
        LogUtils.log_E("测试图片路径"+url);
        ImageView imageView = (ImageView) fl.findViewById(R.id.ig);
        Bitmap bit;
        imgUrl=url;
        bit=getImageThumbnail(url,imageView.getWidth()/4,imageView.getHeight()/4);
        imageView.setImageDrawable(resizeImage(bit, imageView.getWidth(), imageView.getHeight()));
        rotate(imgUrl);
        prepareShare(imgUrl);
    }


    /**
     * 根据指定的图像路径和大小来获取缩略图
     * 此方法有两点好处：
     *     1. 使用较小的内存空间，第一次获取的bitmap实际上为null，只是为了读取宽度和高度，
     *        第二次读取的bitmap是根据比例压缩过的图像，第三次读取的bitmap是所要的缩略图。
     *     2. 缩略图对于原图像来讲没有拉伸，这里使用了2.2版本的新工具ThumbnailUtils，使
     *        用这个工具生成的图像不会被拉伸。
     * @param imagePath 图像的路径
     * @param width 指定输出图像的宽度
     * @param height 指定输出图像的高度
     * @return 生成的缩略图
     */
    private Bitmap getImageThumbnail(String imagePath, int width, int height) {
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        // 获取这个图片的宽和高，注意此处的bitmap为null
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        options.inJustDecodeBounds = false; // 设为 false
        // 计算缩放比
        int h = options.outHeight;
        int w = options.outWidth;
        int beWidth = w / width;
        int beHeight = h / height;
        int be = 1;
        if (beWidth < beHeight) {
            be = beWidth;
        } else {
            be = beHeight;
        }
        if (be <= 0) {
            be = 1;
        }
        options.inSampleSize = be;
        // 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        // 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return bitmap;
    }

    //压缩图片
    private static Bitmap small(Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postScale(0.5f, 0.5f); //长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
        return resizeBmp;
    }
    //指定大小对图片进行压缩

    public static Drawable resizeImage(Bitmap bitmap, int w, int h)
    {
        Bitmap BitmapOrg = bitmap;
        int width = BitmapOrg.getWidth();
        int height = BitmapOrg.getHeight();
        int newWidth = w;
        int newHeight = h;

        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        float n=scaleHeight>scaleWidth?scaleHeight:scaleWidth;

        Matrix matrix = new Matrix();
        matrix.postScale(n, n);
        // if you want to rotate the Bitmap
        // matrix.postRotate(45);
        Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
                height, matrix, true);
        return new BitmapDrawable(resizedBitmap);
    }

    @Override
    public void onStop() {
        LogUtils.log_E("测试fragment stop");
        mOrientationListener.disable();

        // stop the preview
        stopCameraPreview();
        mCamera.release();
        super.onStop();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        mSurfaceHolder = holder;

        getCamera(mCameraID);
        startCameraPreview();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // The surface is destroyed with the visibility of the SurfaceView is set to View.Invisible
    }


    /**
     * A picture has been taken
     * @param data
     * @param camera
     */
    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        int rotation = (
                mDisplayOrientation
                        + mOrientationListener.getRememberedNormalOrientation()
                        + mLayoutOrientation
        ) % 360;

//        Bitmap bitmap = ImageUtility.rotatePicture(getActivity(), rotation, data);
//        Uri uri = ImageUtility.savePicture(getActivity(), bitmap);
        getFragmentManager()
                .beginTransaction()
                .replace(
                        R.id.fragment_container,
                        EditSavePhotoFragment.newInstance(data, rotation, mCoverHeight, mPreviewHeight),
                        EditSavePhotoFragment.TAG)
                .addToBackStack(null)
                .commit();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        this.position=position;
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
    //按钮点击事件  重拍和分享
    @Override
    public void onClick(View v) {
        int id=v.getId();
        switch (id){
            //重拍
            case R.id.ig_remake:
                Utils.showToast("重拍事件");
                startCameraPreview();
                break;
            //分享
            case R.id.ig_share:
                //分享按钮
                break;
        }
    }



    /**
     * When orientation changes, onOrientationChanged(int) of the listener will be called
     */
    private static class CameraOrientationListener extends OrientationEventListener {

        private int mCurrentNormalizedOrientation;
        private int mRememberedNormalOrientation;

        public CameraOrientationListener(Context context) {
            super(context, SensorManager.SENSOR_DELAY_NORMAL);
        }

        @Override
        public void onOrientationChanged(int orientation) {
            if (orientation != ORIENTATION_UNKNOWN) {
                mCurrentNormalizedOrientation = normalize(orientation);
            }
        }

        private int normalize(int degrees) {
            if (degrees > 315 || degrees <= 45) {
                return 0;
            }

            if (degrees > 45 && degrees <= 135) {
                return 90;
            }

            if (degrees > 135 && degrees <= 225) {
                return 180;
            }

            if (degrees > 225 && degrees <= 315) {
                return 270;
            }

            throw new RuntimeException("The physics as we know them are no more. Watch out for anomalies.");
        }

        public void rememberOrientation() {
            mRememberedNormalOrientation = mCurrentNormalizedOrientation;
        }

        public int getRememberedNormalOrientation() {
            return mRememberedNormalOrientation;
        }
    }







    private String imgUrl_share;//分享地址
    //拍照
    public final class TakePictureCallback implements Camera.PictureCallback {
        String path;
        public void onPictureTaken(final byte[] data, Camera camera) {
            if (android.os.Environment.getExternalStorageState().equals(
                    android.os.Environment.MEDIA_MOUNTED)) {
                path=Constans.PIC_SHARE;
            } else{
                path=Constans.PIC_SHARE_DATA;
            }
            final String picUrl = path+ "/" + System.currentTimeMillis() + ".jpg";
            File dir = new File(path);
                        if (!dir.exists()) {
                            dir.mkdir();
                            LogUtils.log_E("not exists");
                        }
            LogUtils.log_E("测试sd卡保存路径："+picUrl);
//                new Thread(){
//                    @Override
//                    public void run() {
//                        Bitmap bitmap;
//
//                        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
//                        bitmap = Utils.rotateBitmapByDegree(bitmap, 90);
//                        File dir = new File(Constans.PIC_SHARE);
////                      ig_new.setImageBitmap(bitmap);
//                        if (!dir.exists()) {
//                            dir.mkdir();
//                            LogUtils.log_E("not exists");
//                        }
//                        File file = new File(picUrl);
//                        FileOutputStream outputStream = null;
//                        try {
//                            outputStream = new FileOutputStream(file);
//                            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
//                            outputStream.close();
//                            bitmap=null;
//                            file=null;
//                            isReadable=true;
////                            testCamera(picUrl);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//
//                    }
//                }.start();


            camera.stopPreview();
            imgUrl_share = Constans.PIC_SHARE + "/" + System.currentTimeMillis()+"testshare" + ".jpg";
            int rotation = (
                    mDisplayOrientation
                            + mOrientationListener.getRememberedNormalOrientation()
                            + mLayoutOrientation
            ) % 360;
            rotatePicture(rotation,data,ig_new);
            prepareShare(picUrl);
//                camera.startPreview();//

        }
    }
    private ImageView ig_new;//用于显示拍照后的图片
    private RelativeLayout fl_new;//用于截屏
    private ImageView ig_chongpai;//重拍按钮
    private ImageView ig_share;//分享按钮
    private RelativeLayout fl;//拍照界面
    private BitmapUtils bitmapUtils;
    private boolean isReadable;
    private RelativeLayout rl_share_choose;//分享选择菜单
    private SquareCameraPreview pre;
    private ImageView ig_fanzhuan;//反转摄像头
    private ImageView ig_pic;
    //初始化相框
    public void initViewPager(View v){
        ig_pic= (ImageView) v.findViewById(R.id.ig);
        ig_fanzhuan= (ImageView) v.findViewById(R.id.ig_fanzhuan);
        //反转摄像头
        ig_fanzhuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCameraID == CameraInfo.CAMERA_FACING_FRONT) {
                    mCameraID = getBackCameraID();
                } else {
                    mCameraID = getFrontCameraID();
                }
                restartPreview();
            }
        });
        pre= (SquareCameraPreview) v.findViewById(R.id.camera_preview_view);
        ShareSDK.initSDK(getActivity());
        ig= (ImageView) v.findViewById(R.id.ig_close);
        ig.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(rl_share_menu.getVisibility()==View.VISIBLE){
                    startCameraPreview();
                }else{
                    getActivity().finish();
                }
            }
        });
        bitmapUtils=new BitmapUtils(getActivity());
        ig_chongpai= (ImageView) v.findViewById(R.id.ig_remake);
        ig_share= (ImageView) v.findViewById(R.id.ig_share);
        ig_chongpai.setOnClickListener(this);
        ig_share.setOnClickListener(this);
        fl= (RelativeLayout) v.findViewById(R.id.fl);
        fl_new = (RelativeLayout) v.findViewById(R.id.fl_new);
        ig_new = (ImageView) v.findViewById(R.id.ig_new);
        ig_back= (ImageView) v.findViewById(R.id.ig_back);
        rl_menu = (RelativeLayout) v.findViewById(R.id.rl_menu);
        rl_share_menu = (RelativeLayout) v.findViewById(R.id.rl_share_menu);
        rl_share_choose= (RelativeLayout) v.findViewById(R.id.rl_share_choose);

        ImageView ig_weibo= (ImageView) v.findViewById(R.id.ig_weibo);
        ImageView ig_wechat= (ImageView) v.findViewById(R.id.ig_wechat);
        //微信分享
        ig_wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtils.log_E("测试微信分享"+imgUrl_share);
//                weiXinWebShare(false, getActivity(), new String[]{"测试微信图片分享", imgUrl_share});
                showShare();
            }
        });
        //微博分享
        ig_weibo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                weiBoShare(getString(R.string.showPic_title), imgUrl_share);
            }
        });


        ImageView ig_share= (ImageView) rl_share_menu.findViewById(R.id.ig_share);
        ig_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShare();
            }
        });
        vp= (ViewPager) v.findViewById(R.id.vp);
        mAdapter=new FragmentAdapter( getActivity().getSupportFragmentManager());
        flist=new ArrayList<Fragment>();
        PicFragment f1=new PicFragment();
        Bundle bundle=new Bundle();
        bundle.putString("flag", "0");
        f1.setArguments(bundle);
        PicFragment f2=new PicFragment();
        Bundle b2=new Bundle();
        b2.putString("flag", "1");
        f2.setArguments(b2);
        flist.add(f1);
        flist.add(f2);
        mAdapter.setList(flist);
        vp.setAdapter(mAdapter);
        vp.setOnPageChangeListener(this);
    }



    private ImageView ig_back;





    //׼准备分享
    public void prepareShare(final String picUrl) {
//        fl.setVisibility(View.INVISIBLE);
//        fl_new.setVisibility(View.VISIBLE);
        rl_menu.setVisibility(View.INVISIBLE);
        rl_share_menu.setVisibility(View.VISIBLE);
        getPic(picUrl);


    }




    private Bitmap shot(Activity activity) {
        //View是你需要截图的View
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap b1 = view.getDrawingCache();
        // 获取状态栏高度 /
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;
        Log.i("TAG", "" + statusBarHeight);
        // 获取屏幕长和高
        int width = activity.getWindowManager().getDefaultDisplay().getWidth();
        int height = activity.getWindowManager().getDefaultDisplay().getHeight();
        // 去掉标题栏
        Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
        view.destroyDrawingCache();
        return b;
    }



    //将界面上的控件转化为图片
    public void getPic(String picPath) {

        final Bitmap bmp = Bitmap.createBitmap(fl_new.getWidth(), fl_new.getHeight(), Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bmp);
        fl_new.draw(canvas);
        final String photoUrl = picPath;//换成自己的图片保存路径
        final File file = new File(photoUrl);
        new Thread() {
            @Override
            public void run() {

                boolean bitMapOk = false;
                try {
                    bitMapOk = bmp.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(file));
                } catch (FileNotFoundException e) {
                }
                if (bitMapOk) {
                }

            }
        }.start();

        //通知系统更新相册  使用户能够通过相册访问自拍图片
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        getActivity().sendBroadcast(intent);//这个广播的目的就是更新图库，发了这个广播进入相册就可以找到你保存的图片了！，记得要传你更新的file哦

    }











    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void rotatePicture(int rotation, byte[] data, ImageView photoImageView) {
        Bitmap bitmap = ImageUtility.decodeSampledBitmapFromByte(getActivity(), data);
        if (rotation != 0) {
            Bitmap oldBitmap = bitmap;
            Matrix matrix = new Matrix();
            matrix.postRotate(rotation);
            bitmap = Bitmap.createBitmap(
                    oldBitmap, 0, 0, oldBitmap.getWidth(), oldBitmap.getHeight(), matrix, false
            );

            oldBitmap.recycle();
        }
        photoImageView.setBackground(Utils.resizeImage(bitmap, ig_new.getWidth(), ig_new.getHeight()));
        switch (position){
            case 0:
                ig_back.setBackgroundResource(R.drawable.zipaikuang1);
                break;
            case 1:
                ig_back.setBackgroundResource(R.drawable.zipaikuang2);
                break;
            case 2:
                ig_back.setBackgroundResource(R.drawable.border3);
                break;
        }
    }

    public void rotate(String imgUrl){
        Bitmap bit;
        bit=getImageThumbnail(imgUrl,ig_new.getWidth()/4,ig_new.getHeight()/4);
        ig_new.setImageDrawable(resizeImage(bit, ig_new.getWidth(), ig_new.getHeight()));

        switch (position){
            case 0:
                ig_back.setBackgroundResource(R.drawable.zipaikuang1);
                break;
            case 1:
                ig_back.setBackgroundResource(R.drawable.zipaikuang2);
                break;
            case 2:
                ig_back.setBackgroundResource(R.drawable.border3);
                break;
        }
    }





    //微博分享（图片分享）
    public void weiBoShare(String title, String imagePath) {
        Platform wb = ShareSDK.getPlatform(SinaWeibo.NAME);
        Platform.ShareParams sp = new SinaWeibo.ShareParams();
        sp.setTitle(title);
        sp.setImagePath(imagePath);
        wb.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                Utils.showToast(getString(R.string.share_success));

            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Utils.showToast(getString(R.string.share_failed));
            }

            @Override
            public void onCancel(Platform platform, int i) {
                Utils.showToast(getString(R.string.share_cancle));
            }
        });
        wb.share(sp);

    }




    private Context context;

    //微信分享(图片分享)
    public void weiXinWebShare(boolean isWeixin, Context mContext, String... args) {
        if (null == mContext || args.length < 1) {
//            MainApplication.getIns().tip('分享失败');
            LogUtils.log_E("mCon==null");
            return;
        } else {
            this.context = mContext;
            for (int i = 0; i < args.length; i++) {
                String str = args[i];
                if (TextUtils.isEmpty(str) && i != 2) {
//                    MainApplication.getIns().tip('分享失败');分享失败
                    LogUtils.log_E("isempty");
                    return;
                }
            }
            String title = args[0];
            String image = args[1];
            LogUtils.log_E("测试"+image);
            WechatHelper.ShareParams sp = null;
            if (isWeixin) {
                sp = new Wechat.ShareParams();
            } else {
                LogUtils.log_E("测试sp");
                sp = new WechatMoments.ShareParams();
            }
            sp.title = title;

            if (TextUtils.isEmpty(image)) {
                sp.imageData = ((BitmapDrawable) context.getResources().getDrawable(R.drawable.biankuang)).getBitmap();
            } else {
                LogUtils.log_E("测试bit");
                sp.imageData = BitmapFactory.decodeFile(image);
            }

            sp.setShareType(Platform.SHARE_IMAGE);
            Platform plat = null;
            if (isWeixin) {
                plat = ShareSDK.getPlatform(Wechat.NAME);
            } else {
                LogUtils.log_E("platForm");
                plat = ShareSDK.getPlatform(WechatMoments.NAME);
            }
            plat.setPlatformActionListener(new PlatformActionListener() {
                @Override
                public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
//                    Utils.showToast(getString(R.string.share_success));
                }

                @Override
                public void onError(Platform platform, int i, Throwable throwable) {
//                    Utils.showToast(getString(R.string.share_failed));
                }

                @Override
                public void onCancel(Platform platform, int i) {
//                    Utils.showToast(getString(R.string.share_cancle));
                }
            });
            plat.share(sp);
            LogUtils.log_E("platForm   share");
        }
    }





    private void showShare() {
        ShareSDK.initSDK(getActivity());
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
//        oks.setTitle(getString(R.string.share));
        oks.setImagePath(imgUrl_share);
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
//        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
//        oks.setText("我是分享文本");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
//        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
//        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
//        oks.setSiteUrl("http://sharesdk.cn");

// 启动分享GUI
        oks.show(getActivity());
    }





}
